package handler

import (
	"time"

	"github.com/project-flogo/core/data/coerce"
)

type EdgeChannelParams struct {
	EdgeChannelID string        `mapstructure:"edgeChannelId" md:"edgeChannelId" json:"edgeChannelId,omitempty"`
	DataType      string        `mapstructure:"dataType" md:"dataType" json:"dataType,omitempty"`
	MetricDataID  string        `mapstructure:"metricDataId" md:"metricDataId" json:"metricDataId,omitempty"`
	Mode          string        `mapstructure:"mode" md:"mode" json:"mode,omitempty"`
	Interval      time.Duration `mapstructure:"interval" md:"interval" json:"interval,omitempty"`
	MinThreshold  float64       `mapstructure:"minThreshold" md:"minThreshold" json:"minThreshold,omitempty"`
}

func (e *EdgeChannelParams) ToMap() map[string]interface{} {
	return map[string]interface{}{
		"edgeChannelId": e.EdgeChannelID,
		"dataType":      e.DataType,
		"metricDataId":  e.MetricDataID,
		"mode":          e.Mode,
		"interval":      e.Interval.String(),
		"minThreshold":  e.MinThreshold,
	}
}

func mapToEdgeChannelParams(values map[string]interface{}) (EdgeChannelParams, error) {
	e := EdgeChannelParams{}
	channelId, err := coerce.ToString(values["edgeChannelId"])
	if err != nil {
		return EdgeChannelParams{}, err
	}
	e.EdgeChannelID = channelId

	dataType, err := coerce.ToString(values["dataType"])
	if err != nil {
		return EdgeChannelParams{}, err
	}
	e.DataType = dataType

	metricDataId, err := coerce.ToString(values["metricDataId"])
	if err != nil {
		return EdgeChannelParams{}, err
	}
	e.MetricDataID = metricDataId

	mode, err := coerce.ToString(values["mode"])
	if err != nil {
		return EdgeChannelParams{}, err
	}
	e.Mode = mode

	interval, err := coerce.ToString(values["interval"])
	if err != nil {
		return EdgeChannelParams{}, err
	}
	d, err := time.ParseDuration(interval)
	if err != nil {
		return EdgeChannelParams{}, err
	}
	e.Interval = d

	mh, err := coerce.ToFloat64(values["minThreshold"])
	if err != nil {
		return EdgeChannelParams{}, err
	}
	e.MinThreshold = mh

	return e, nil
}
